package com.yyf.kafka.controller;

import com.alibaba.fastjson.JSON;
import com.yyf.kafka.common.ErrorCode;
import com.yyf.kafka.common.Response;
import com.yyf.kafka.dto.MessageEntity;
import com.yyf.kafka.producer.SimpleProducer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * 壹 * @Author: yang
 * 貮 * @Date: 2019/11/5 15:12
 */

@Slf4j
@Api(tags = "生产者测试接口")
@RestController
@RequestMapping("/kafka")
public class ProduceController {

	@Autowired
	private SimpleProducer simpleProducer;

	@Value("${kafka.topic.default}")
	private String topic;

	@ApiOperation(value = "hello kafka")
	@RequestMapping(value = "/hello", method = RequestMethod.GET, produces = {"application/json"})
	public Response sendKafka() {
		return new Response(ErrorCode.SUCCESS, "OK");
	}

	@ApiOperation(value = "生产者发送消息")
	@RequestMapping(value = "/send", method = RequestMethod.POST, produces = {"application/json"})
	public Response sendKafka(@RequestBody MessageEntity message) {
		try {
			log.info("kafka的消息={}", JSON.toJSON(message));
			simpleProducer.send(topic, "key", message);
			log.info("发送kafka成功.");
			return new Response(ErrorCode.SUCCESS, "发送kafka成功");
		} catch (Exception e) {
			log.error("发送kafka失败", e);
			return new Response(ErrorCode.EXCEPTION, "发送kafka失败");
		}
	}
}
